package com.example.teaching_server.dto;

import com.example.teaching_server.entity.Resource;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 资源信息DTO
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "资源详细信息")
public class ResourceDTO {

    @NotNull(message = "资源ID不能为空")
    @Positive(message = "资源ID必须是正整数")
    @Schema(description = "资源唯一标识", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
    private Long id;

    @NotBlank(message = "资源名称不能为空")
    @Schema(description = "资源名称", example = "数学课件第一章", requiredMode = Schema.RequiredMode.REQUIRED)
    private String name;

    @NotBlank(message = "资源类型不能为空")
    @Schema(description = "资源类型", example = "课件", requiredMode = Schema.RequiredMode.REQUIRED)
    private String type;

    @Schema(description = "文件大小（人类可读格式）", example = "2.5 MB")
    private String size;

    @Schema(description = "文件大小（字节数）", example = "2621440")
    private Long sizeInBytes;

    @JsonFormat(pattern = "yyyy-MM-dd")
    @Schema(description = "创建日期", example = "2024-03-01")
    private String date;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @Schema(description = "创建时间", example = "2024-03-01 10:30:00")
    private LocalDateTime createdAt;

    @NotBlank(message = "文件类型不能为空")
    @Schema(description = "文件MIME类型", example = "application/pdf", requiredMode = Schema.RequiredMode.REQUIRED)
    private String fileType;

    @Schema(description = "文件扩展名", example = "pdf")
    private String fileExtension;

    @Schema(description = "文件下载URL", example = "/api/resources/1/download")
    private String downloadUrl;

    @Schema(description = "文件预览URL", example = "/api/resources/1/preview")
    private String previewUrl;

    @Schema(description = "资源描述", example = "高中数学第一章课件")
    private String description;

    @Positive(message = "下载次数不能为负数")
    @Schema(description = "下载次数", example = "150")
    private Integer downloadCount;

    @Schema(description = "资源标签", example = "数学,课件,高中")
    private String tags;

    @Schema(description = "所属学科", example = "数学")
    private String subject;

    @Schema(description = "上传者ID", example = "123")
    private Integer uploaderId;

    /**
     * 从实体类构造（修复版）
     */
    public ResourceDTO(Resource resource) {
        this.id = resource.getId();
        this.name = resource.getName();
        this.type = resource.getType();
        this.size = resource.getSize();
        this.sizeInBytes = parseSizeToBytes(resource.getSize());
        this.date = resource.getCreatedAt().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        this.createdAt = resource.getCreatedAt();
        this.fileType = resource.getFileType();
        this.fileExtension = extractFileExtension(resource.getName());
        this.subject = resource.getSubject(); // 使用实体类中存在的字段
        this.uploaderId = resource.getUploaderId(); // 使用实体类中存在的字段

        // 为不存在的字段设置默认值
        this.description = ""; // 实体类中没有description字段
        this.downloadCount = 0; // 实体类中没有downloadCount字段
        this.tags = ""; // 实体类中没有tags字段
    }

    /**
     * 解析文件大小为字节数
     */
    private Long parseSizeToBytes(String sizeStr) {
        if (sizeStr == null) return 0L;

        try {
            if (sizeStr.toUpperCase().endsWith("KB")) {
                double kb = Double.parseDouble(sizeStr.replace("KB", "").trim());
                return (long) (kb * 1024);
            } else if (sizeStr.toUpperCase().endsWith("MB")) {
                double mb = Double.parseDouble(sizeStr.replace("MB", "").trim());
                return (long) (mb * 1024 * 1024);
            } else if (sizeStr.toUpperCase().endsWith("GB")) {
                double gb = Double.parseDouble(sizeStr.replace("GB", "").trim());
                return (long) (gb * 1024 * 1024 * 1024);
            } else if (sizeStr.toUpperCase().endsWith("B")) {
                return Long.parseLong(sizeStr.replace("B", "").trim());
            }
        } catch (NumberFormatException e) {
            // 解析失败，返回0
        }
        return 0L;
    }

    /**
     * 提取文件扩展名
     */
    private String extractFileExtension(String fileName) {
        if (fileName == null || !fileName.contains(".")) {
            return "";
        }
        return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
    }

    /**
     * 判断是否为图片文件
     */
    @Schema(description = "是否为图片文件", accessMode = Schema.AccessMode.READ_ONLY)
    public boolean isImage() {
        return fileType != null && fileType.startsWith("image/");
    }

    /**
     * 判断是否为文档文件
     */
    @Schema(description = "是否为文档文件", accessMode = Schema.AccessMode.READ_ONLY)
    public boolean isDocument() {
        return fileType != null && (
                fileType.startsWith("application/") ||
                        fileType.equals("text/plain") ||
                        fileType.contains("pdf") ||
                        fileType.contains("word") ||
                        fileType.contains("excel")
        );
    }

    /**
     * 判断是否为视频文件
     */
    @Schema(description = "是否为视频文件", accessMode = Schema.AccessMode.READ_ONLY)
    public boolean isVideo() {
        return fileType != null && fileType.startsWith("video/");
    }

    /**
     * 获取文件图标类型
     */
    @Schema(description = "文件图标类型", accessMode = Schema.AccessMode.READ_ONLY)
    public String getFileIcon() {
        if (isImage()) return "image";
        if (isDocument()) return "document";
        if (isVideo()) return "video";
        if ("pdf".equalsIgnoreCase(fileExtension)) return "pdf";
        if (fileExtension.matches("doc|docx")) return "word";
        if (fileExtension.matches("xls|xlsx")) return "excel";
        if (fileExtension.matches("ppt|pptx")) return "powerpoint";
        return "file";
    }

    /**
     * 获取格式化后的创建时间
     */
    @Schema(description = "格式化创建时间", accessMode = Schema.AccessMode.READ_ONLY)
    public String getFormattedCreatedAt() {
        if (createdAt == null) return "";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        return createdAt.format(formatter);
    }
}
